﻿

var viewDistrictModel = new function () {

    this.Districts = ko.observableArray(data.ListDistrict);
    this.CurrentPageIndex = ko.observable(1);
    this.PageSize = ko.observable(10);
    this.PageText = ko.computed(function () {
        var total = this.Districts().length;
        if (total == 1)
            return total + " quận/huyện";
        else
            return total + " quận/huyện";

    }, this);

    this.SetOrder = SetOrder;
    this.colName = ko.observable("DateCreated");
    this.sortOrder = ko.observable("asc");
    this.Keywords = ko.observable("Keywords");

    //Insert max page
    this.maxPageIndex = ko.computed(function () {
        if (this.PageSize() == 0) {
            this.PageSize = ko.observable(10);
        }
        return Math.ceil(ko.utils.unwrapObservable(this.Districts()).length / this.PageSize());
    }, this);

    this.PrevButton = function () {
        this.CurrentPageIndex(this.CurrentPageIndex() - 1);
    };

    this.PrevButtonClass = ko.computed(function () {
        var page = parseInt(this.CurrentPageIndex());
        if (page > 1) {
            return "btn btn-prev-arrow prev-active";
        }
        else {
            return "btn btn-prev-arrow";
        }
    }, this);

    this.NextButtonClass = ko.computed(function () {
        if (this.CurrentPageIndex() == this.maxPageIndex() || this.maxPageIndex() == 1)
            return "btn btn-next-arrow next-disabled";
        else
            return "btn btn-next-arrow";
    }, this);

    this.NextButton = function () {
        this.CurrentPageIndex(this.CurrentPageIndex() + 1);
    };

    this.ItemsOnPage = ko.computed(function () {
        var currentPage = this.CurrentPageIndex();
        var maxPage = this.maxPageIndex();

        if (parseInt(currentPage) == 0)
            this.CurrentPageIndex(1);

        if (parseInt(currentPage) >= parseInt(maxPage)) {
            this.CurrentPageIndex(parseInt(maxPage));
        }
        if (parseInt(this.PageSize()) <= 0) {
            this.PageSize(10);
        }
        var startIndex = this.PageSize() * (this.CurrentPageIndex() - 1);
        var endIndex = parseInt(startIndex) + parseInt(this.PageSize());

        return this.Districts().slice(startIndex, endIndex);
    }, this);

    // Search
    this.SearchButton = function () {
        var keywords = $('#searchKeyword').val();
        FillterData(keywords);
    };
    this.RunSomethingKey = function (viewModel, event) {
        if (event.keyCode == 13 || event.keyCode == 9) {
            this.RunSomething(viewModel, event);
        }
        return true;
    }
    this.RunSomething = function (viewModel, event) {
        var keywords = $('#searchKeyword').val();
        FillterData(keywords);
    }

    function FillterData(keywords) {
        if (keywords != null && keywords != "") {
            var filters = data.ListDistrict;
            viewDistrictModel.Districts([]);

            for (var i = 0; i < filters.length; i++) {
                if (filters[i].Name.toLowerCase().indexOf(keywords.toLowerCase()) > -1 || filters[i].StateName.toLowerCase().indexOf(keywords.toLowerCase()) > -1 || filters[i].StateId.toLowerCase().indexOf(keywords.toLowerCase()) > -1) {
                    viewDistrictModel.Districts().push(filters[i]);
                }
            }

            viewDistrictModel.Districts(viewDistrictModel.Districts());
        }
        else {
            viewDistrictModel.Districts(data.ListDistrict);
        }
    }

    // Sort 
    function SetOrder(event, colName) {
        if (viewDistrictModel.colName() === colName) {
            switchSortOrder();
        }
        else {
            viewDistrictModel.colName(colName);
            viewDistrictModel.sortOrder("desc");
        }
        SetTHClass(event, colName);
        if (colName != "")
            this.Districts(SortByPropertyName(ko.utils.unwrapObservable(viewDistrictModel.Districts()), colName, viewDistrictModel.sortOrder()));
    }
    this.SetOrder = SetOrder;

    function SetTHClass(event, colName) {
        //remove the existing classes
        $("div.title").parent().find(".sort_wrapper").children("span").removeClass("asc");
        $("div.title").parent().find(".sort_wrapper").children("span").removeClass("desc");

        if (viewDistrictModel.sortOrder() === "asc") {
            $("#" + colName + " span").addClass("asc");

        } else {
            $("#" + colName + " span").addClass("desc");
        }
    }

    function switchSortOrder() {
        if (viewDistrictModel.sortOrder() === "asc") {
            viewDistrictModel.sortOrder("desc");
        } else {
            viewDistrictModel.sortOrder("asc");
        }
    }

    // sort all items
    function SortByPropertyName(items, propertyName, sortOrder) {
        return items.sort(sortProperty(propertyName, sortOrder));
    }
    function sortProperty(property, sortOrder) {
        if (sortOrder == "asc")
            return function (a, b) {
                if (a[property] != null && b[property] != null) {
                    if (typeof a[property] === "boolean") {
                        return (a[property] > b[property]) ? -1 : (a[property] < b[property]) ? 1 : 0;
                    }
                    else if (typeof a[property] === "number") {
                        var number = parseFloat(a[property]);
                        if (number != NaN && number > 0)
                            return (parseFloat(a[property]) < parseFloat(b[property])) ? -1 : (parseFloat(a[property]) > parseFloat(b[property])) ? 1 : 0;
                        else
                            return (a[property].toLowerCase() < b[property].toLowerCase()) ? -1 : (a[property].toLowerCase() > b[property].toLowerCase()) ? 1 : 0;
                    }
                    else {
                        var number = parseFloat(a[property].toLowerCase());
                        if (number != NaN && number > 0)
                            return (parseFloat(a[property]) < parseFloat(b[property])) ? -1 : (parseFloat(a[property]) > parseFloat(b[property])) ? 1 : 0;
                        else
                            return (a[property].toLowerCase() < b[property].toLowerCase()) ? -1 : (a[property].toLowerCase() > b[property].toLowerCase()) ? 1 : 0;
                    }
                }
            }
        else
            return function (a, b) {
                if (a[property] != null && b[property] != null) {

                    if (typeof a[property] === "boolean") {
                        return (a[property] > b[property]) ? -1 : (a[property] < b[property]) ? 1 : 0;
                    }
                    else if (typeof a[property] === "number") {
                        var number = parseFloat(a[property]);
                        if (number > 0)
                            return (parseFloat(a[property]) > parseFloat(b[property])) ? -1 : (parseFloat(a[property]) < parseFloat(b[property])) ? 1 : 0;
                        else
                            return (a[property].toLowerCase() > b[property].toLowerCase()) ? -1 : (a[property].toLowerCase() < b[property].toLowerCase()) ? 1 : 0;
                    }
                    else {
                        var number = parseFloat(a[property].toLowerCase());
                        if (number > 0)
                            return (parseFloat(a[property]) > parseFloat(b[property])) ? -1 : (parseFloat(a[property]) < parseFloat(b[property])) ? 1 : 0;
                        else
                            return (a[property].toLowerCase() > b[property].toLowerCase()) ? -1 : (a[property].toLowerCase() < b[property].toLowerCase()) ? 1 : 0;
                    }
                }
            }
    }

    // Delete
    this.DeleteDistrict = function () {
        var districtId = $('#districtId').val();

        var url = "/Management/DistrictList/Delete?id=" + districtId;

        // Append message waiting
        $('#processing').html("<font color='read'>Waiting for delete this district...</font>");

        // Json Get function to retrive data from server
        $.getJSON(url, function (data) {
            if (data != null && data != undefined) {

                viewDistrictModel.Districts(data.ListDistrict);

                // Close message waiting
                $.fancybox.close();
                $('#processing').html("");
            }
        });
    };
}

ko.applyBindings(viewDistrictModel, document.getElementById("main"));

function DeleteDialog(id) {
    $('#districtId').val(id);
    $('#districtname').text($('#district' + id).attr("rel"));
}